define( [
  'require',
  'jquery',
  'api',
  'bigwe_utils',
  'message',
  './utils',
  'imgChoose',
  'mpnewsChoose',
  'videoUploader',
  'videoChoose',
  'bigwe_component'
], function( require, $ ) {

  var BIGWE_API = require( 'api' );
  var ShowTitleMessage = require( 'message' );

  var utils = require( './utils' );
  var ic = require( 'imgChoose' );
  var vu = require( 'videoUploader' );
  var vc = require( 'videoChoose' );
  var bu = require( 'bigwe_utils' );
  var mpc = require( 'mpnewsChoose' );
  var bc = require( 'bigwe_component' );

  var showTime = ShowTitleMessage.showTime;
  var htmlBuild = utils.htmlBuild;

  var returnParam = {};
  var me = $( '#auto_reply' ),
    thisApis = BIGWE_API.AUTO_REPLY;
  // 取得appid

  var appid;
  var verify_info;
  // 取得appid
  returnParam.init = function( data ) {
    data = data || {};
    replyData.beadded.app_id = replyData.autoReply.app_id = appid = data.app_id;
    verify_info = data.verify_type_info * 1;
    verifyCheck( verify_info );
  }

  returnParam.tabChange = function() {
    autoReplyMaterialCallback /*[$('#auto_reply .reply_type_group .selected').index() || 0]*/ .call( window, $( '#auto_reply .reply_type_group .btn_item.selected' ).index() );
    var textEdit = $( '#auto_reply .replymsg1 .tab_nav.selected' );
    if ( textEdit.hasClass( 'tab_appmsg' ) ) {

      $( '#auto_reply .replymsg1 .tab_nav.tab_text' ).trigger( 'click' );
      /*var p = $('#auto_reply .replymsg1 .js_editorArea')[0],
          s = window.getSelection(),
          r = document.createRange();
      r.setStart(p, 0);
      r.setEnd(p, 0);
      s.removeAllRanges();
      s.addRange(r);*/
    }
  }

  // 初始化已设置的数据
  var dataInit = [
    function( before, after ) {
      var beadded = $( '.replymsg1', me );

      if ( !this[ 'autoReplyFlag' + 0 ] ) {

        $( '.mask_loadData', beadded ).fadeIn();
        $( '.delete_reply', beadded ).prop( 'disabled', 'disabled' );
        if ( typeof after === 'undefined' ) {
          after = before;
          before = undefined;
        }

        if ( $.isFunction( before ) ) {
          before();
        }
        $.ajax( {
          url: thisApis.GET_BEADDEDREPLY,
          type: 'post',
          data: {
            app_id: appid
          },
          success: function( data ) {
            data = $.parseJSON( data );
            htmlAndDataset.beaddedSetAttrbute( data.data.data );
            this[ 'autoReplyFlag' + 0 ] = !0;
            if ( data.data.data ) {
              $( '.delete_reply', beadded ).removeAttr( 'disabled' );
            }

            if ( $.isFunction( after ) ) {
              after.apply( window, arguments );
            }
          },
          complete: function() {
            $( '.mask_loadData', beadded ).fadeOut();
          }
        } );
      }
    },
    function( before, after ) {
      var autoReply = $( '.replymsg2', me );
      if ( !this[ 'autoReplyFlag' + 1 ] ) {
        $( '.mask_loadData', autoReply ).fadeIn();
        $( '.delete_reply', autoReply ).prop( 'disabled', 'disabled' );
        if ( typeof after === 'undefined' ) {
          after = before;
          before = undefined;
        }

        if ( $.isFunction( before ) ) {
          before();
        }
        $.ajax( {
          url: thisApis.GET_AUTOREPLY,
          type: 'post',
          data: {
            app_id: appid
          },
          success: function( data ) {
            data = $.parseJSON( data );
            htmlAndDataset.autoReplySetAttrbute( data.data.data );
            this[ 'autoReplyFlag' + 1 ] = !0;
            if ( $.isFunction( after ) ) {
              after.apply( window, arguments );
            }
            if ( data.data.data ) {
              $( '.delete_reply', autoReply ).removeAttr( 'disabled' );
            }
          },
          complete: function() {
            $( '.mask_loadData', autoReply ).fadeOut();
          }
        } );
      }
    },
    function( before, after ) {

      if ( !this[ 'autoReplyFlag' + 2 ] ) {
        htmlAndDataset.keywordReply.freshReset().freshRules( before, after );
      }
    }
  ];

  function autoReplyMaterialCallback( index ) {

    index = index || 0;
    dataInit[ index ].call( window, refreshBefore, refreshAfter );
    mpc.mpnewsChooseCallback = function( param ) {

      var mpnews = [];
      for ( i in param.mpnewsArray.articles ) {
        temp = param.mpnewsArray.articles[ i ];
        mpnews.push( {
          title: temp.title,
          digest: temp.summary,
          content_url: '/_article?p=' + temp.cd,
          cover_url: temp.cover
        } );
      }

      htmlAndDataset.keywordReply.replyContent[ 4 ]( {
        type: 'news',
        article_group: param.mpnewsArray.article_group,
        article: mpnews
      } ).appendTo( $( '.reply_content_list', currentRuleDom ) );

      htmlAndDataset.keywordReply.countCacul.call( currentRuleDom );
      //var html = htmlBuild.getGraphHtml();
    }

    ic.imagesChooseCallback = function( callbackParam ) {
      var param = {
        type: 'img',
        img_url: callbackParam
      };
      if ( index === 0 ) {
        htmlAndDataset.beaddedSetAttrbute( param );
      } else if ( index === 1 ) {
        htmlAndDataset.autoReplySetAttrbute( param );
      } else if ( index === 2 ) {
        htmlAndDataset.keywordReply.replyContent[ 1 ]( {
          type: 'img',
          img_url: callbackParam
        } ).appendTo( $( '.reply_content_list', currentRuleDom ) );
        htmlAndDataset.keywordReply.countCacul.call( currentRuleDom );
      } else return;

    }

    vc.videoChooseCallback = function( callbackParam ) {
      var video = callbackParam.videoObj,
        param = {
          type: 'video',
          video_title: video.title,
          video_url: video.address,
          video_summary: video.synopsis,
          video_id: video.video_id
        };
      if ( index === 0 ) {
        htmlAndDataset.beaddedSetAttrbute( param );
      } else if ( index === 1 ) {
        htmlAndDataset.autoReplySetAttrbute( param );
      } else if ( index === 2 ) {
        htmlAndDataset.keywordReply.replyContent[ 3 ]( {
          type: 'video',
          video_title: video.title,
          video_url: video.address,
          video_synopsis: video.synopsis,
          video_id: video.video_id
        } ).appendTo( $( '.reply_content_list', currentRuleDom ) );
        htmlAndDataset.keywordReply.countCacul.call( currentRuleDom );
      } else return;
    }

    /*
     *2016年8月8日16:00:48，上传视频 确定 sherlockl
     */
    vu.doSave = function( htm, data ) {
      var param = {
        type: 'video',
        video_id: data.video_id,
        video_url: data.address,
        video_title: data.title,
        video_summary: data.synopsis,
      };
      if ( index === 0 ) {
        htmlAndDataset.beaddedSetAttrbute( param );
      } else if ( index === 1 ) {
        htmlAndDataset.autoReplySetAttrbute( param );
      } else return;
    }

    /*
     *2016年8月8日16:00:48，上传图片 确定 sherlockl
     */
    utils.imgOnSave = function( data ) {
      var param = {
        type: 'img',
        img_url: data.image
      };
      if ( index === 0 ) {
        htmlAndDataset.beaddedSetAttrbute( param );
      } else if ( index === 1 ) {
        htmlAndDataset.autoReplySetAttrbute( param );
      } else return;
    }
  };

  me.on( 'click', '.btn_item', function() {
    var thisIndex = $( this ).index();
    $( this ).addClass( 'selected' ).siblings().removeClass( 'selected' );
    $( '.prompt_msg .gray', me ).eq( thisIndex ).removeClass( 'hide' ).siblings().addClass( 'hide' );
    $( '.keyword_content' ).eq( thisIndex ).removeClass( 'hide' ).siblings().addClass( 'hide' );
    autoReplyMaterialCallback /*[thisIndex || 0]*/ ( thisIndex );
    if ( thisIndex === 1 && $( '#auto_reply .replymsg2 .tab_appmsg.selected' ).hasClass( 'selected' ) ) {
      $( '#auto_reply .replymsg2 .tab_text' ).trigger( 'click' );
    }
  } ).on( 'click', '.wait_content .del_content', function() {
    $( this ).parent().hide().empty().prev().show();
  } ).on( 'click', '.on_server, .out_of_server', function() {
    ShowTitleMessage.show( '应用中...' );
    var thisBtn = $( this );
    thisBtn.prop( 'disabled', 'disabled' )
    $.ajax( {
      type: 'post',
      url: thisApis.STOP_AUTOREPLY,
      data: {
        app_id: appid
      },
      success: function( data ) {
        data = $.parseJSON( data );
        if ( !data.ret ) {
          var status = data.data.status * 1;
          if ( status == 2 ) {
            ShowTitleMessage.show( '停用成功！', showTime );
            $( '#stop_msg', me ).hide();
            $( '.autoReplyClosed', me ).removeClass( 'hide' );
            $( '.autoReplyOpened', me ).addClass( 'hide' );
          } else {
            $( '.autoReplyClosed', me ).addClass( 'hide' );
            $( '.autoReplyOpened', me ).removeClass( 'hide' );
            ShowTitleMessage.show( '启用成功！', showTime );
            refreshAll();
          }
        } else {
          ShowTitleMessage.showWarning( '操作失败，请重试', showTime );
        }
      },
      complete: function() {
        thisBtn.removeAttr( 'disabled' );
      }
    } );
  } );

  $( '.out_of_server', me ).hover( function() {
    $( '#stop_msg', me ).show();
  }, function() {
    $( '#stop_msg', me ).hide();
  } );

  function verifyCheck( verify_info ) {
    if ( verify_info != 0 ) {
      $( '.reply_type_group .verify', me ).addClass( 'hide' );
      $( '.reply_type_group .btn_item', me ).eq( 0 ).trigger( 'click' );
    } else {
      $( '.reply_type_group .verify', me ).removeClass( 'hide' );
    }
  };

  function refreshBefore() {
    if ( !window.isOpened ) {
      window.isOpened = !0;
      // 停启用状态
      $( '#auto_reply>.spinner' ).show();
      $( '.autoReplyClosed', me ).addClass( 'hide' );
      $( '.autoReplyOpened', me ).addClass( 'hide' );
    }
  }

  function refreshAfter( data ) {
    $( '#auto_reply>.spinner' ).hide();
    var status = data.data.status * 1;
    if ( status != 2 ) {
      $( '.autoReplyClosed', me ).addClass( 'hide' );
      $( '.autoReplyOpened', me ).removeClass( 'hide' );
    } else {
      $( '.autoReplyClosed', me ).removeClass( 'hide' );
      $( '.autoReplyOpened', me ).addClass( 'hide' );
    }
  }

  function refreshAll() {
    resetContent();
    window.isOpened = 0;
    for ( i in dataInit ) {
      window[ 'autoReplyFlag' + i ] = 0;
      if ( $( '#auto_reply' ).css( 'display' ) != 'none' ) {
        dataInit[ i ].call( window, refreshBefore, refreshAfter );
      }
    }
    for ( i in replyData ) {
      replyData[ i ] = {
        app_id: appid
      }
    }
  }

  returnParam.autoReplyObjChange = function( param ) {
    param = param || {};
    verifyCheck( param.verify_type_info );
    appid = param.app_id;
    refreshAll();
  }

  function resetContent() {
    $( '.jsMsgSendTab', me ).show()
    $( '.tab_content .wait_content', me ).empty();
    $( '.tab_content .js_editorArea', me ).text( '' ).val( '' ).trigger( 'keyup' );
    $( '.create_new_rule_box .fm_data', me )[ 0 ].reset();
    $( '.keywords_rule_list', me ).empty();
    $( '.nodata_prompt', me ).removeClass( 'hide' );
  }

  var replyData = {
    beadded: {
      app_id: appid
    },
    autoReply: {
      app_id: appid
    }
  };

  var kw = {
    data: function() {
      return {
        app_id: appid,
        create_time: '',
        id: '',
        keywords: [],
        rule_name: '',
        rules: []
      }
    },
    keyword: function() {
      return {
        is_full_match: '1',
        keyword: ''
      }
    },
    rule: function() {
      return {
        type: ''
      }
    }
  };

  var msgType = {
    'text': 0,
    'img': 1,
    'radio': 2,
    'video': 3,
    'news': 4
  }

  function pageChangeRander( totalPage ) {
    var win = this;
    if ( totalPage <= 10 ) {
      $( ".paging", me ).hide();
      return;
    }
    win.pageFirstLoad = 0;
    htmlAndDataset.keywordReply.queryParam.p = 1;
    $( ".paging", me ).pagination( totalPage, {
      num_edge_entries: 2,
      num_display_entries: 4,
      items_per_page: 10,
      prev_text: '上一页',
      next_text: '下一页',
      callback: function( index ) {
        if ( index ) win.pageFirstLoad = !0;
        if ( win.pageFirstLoad ) {
          htmlAndDataset.keywordReply.queryParam.p = ++index;
          htmlAndDataset.keywordReply.freshRules();
        }
      }
    } ).show();
  }
  var htmlAndDataset = {
    beaddedSetAttrbute: function( data ) {
      if ( !data ) return;
      $.extend( replyData.beadded, data );
      if ( !data.type ) {
        ShowTitleMessage.showWarning( '数据异常', showTime );
        return;
      }
      htmlContentAppend[ msgType[ data.type ] ].call( $( '.replymsg1', me ), data );
    },
    autoReplySetAttrbute: function( data ) {
      if ( !data ) return;
      $.extend( replyData.autoReply, data );
      if ( !data.type ) {
        ShowTitleMessage.showWarning( '数据异常', showTime );
        return;
      }
      htmlContentAppend[ msgType[ data.type ] ].call( $( '.replymsg2', me ), data );
    },
    keywordReply: {
      queryParam: {
        app_id: appid,
        search: '',
        p: 1
      },
      init: function( data ) {
        var fnThis = this;
        var ketwordsItemHtml = $.trim( $( '#keywordsHTML' ).html() );

        for ( i in data ) {
          var rule = data[ i ];
          var tempHTML = $( ketwordsItemHtml );
          $( '.head_tab .glyphicon', tempHTML ).css( {
            'transform': 'rotate(180deg)',
            '-webkit-transform': 'rotate(180deg)'
          } );
          $( '.body_tab, .foot_tab', tempHTML ).hide();
          $( '.simple_info', tempHTML ).show();

          $( '.rule_name_text', tempHTML ).html( '规则' + ( parseInt( i ) + 1 ) + '：<span class="name">' + rule.rule_name + '</span>' );
          $( '.ipt_rule_name', tempHTML ).val( rule.rule_name );

          for ( j in rule.keywords ) {
            var keyword = rule.keywords[ j ];
            $( '.simp_kw_list', tempHTML ).append( '<span class="keyword_item">' + keyword.keyword + '</span>' );
            $( '.keyword_list', tempHTML ).append( fnThis.kwordCtrlHtml( keyword ) );
          }

          $( '.simple_keywords', tempHTML ).append( '<span class="updata_date">' + rule.create_time + ' 更新</span>' );

          for ( j in rule.rules ) {
            var content = rule.rules[ j ];
            var contentHtml = fnThis.replyContent[ msgType[ content.type ] ]( content );
            $( '.reply_content_list', tempHTML ).append( contentHtml );
          }

          tempHTML.find( '.reply_type_control .control_item' ).tooltip()
          tempHTML.appendTo( '.keywords_rule_list' ).wrap( '<li class="keywords_rule_item"></li>' ).data( 'keywordData', rule );
          fnThis.countCacul.call( tempHTML );
        }
      },
      countCacul: function() {
        function countCacul( type, arr ) {
          var count = 0;
          for ( i in arr ) {
            if ( arr[ i ].type === type ) {
              count++;
            }
          }

          return count;
        }
        var rules = [];
        $( '.reply_content_list .content_item', this ).each( function() {
          rules.push( $( this ).data( 'ruleData' ) );
        } );
        $( '.simple_reply .sum', this ).text( rules.length );
        $( '.simple_reply .text_count', this ).text( countCacul( 'text', rules ) );
        $( '.simple_reply .img', this ).text( countCacul( 'img', rules ) );
        $( '.simple_reply .video', this ).text( countCacul( 'video', rules ) );
        $( '.simple_reply .news', this ).text( countCacul( 'news', rules ) );
      },
      freshReset: function() {
        var fnThis = this;

        fnThis.resetPage = 0;
        fnThis.queryParam.p = 1;
        $( '.paging', me ).hide();

        return fnThis;
      },
      freshRules: function( before, after ) {
        var fnThis = this;
        var keywordsReply = $( '.replymsg3', me );

        $( '.spinner', keywordsReply ).show();
        $( '.nodata_prompt', keywordsReply ).addClass( 'hide' );
        $.extend( fnThis.queryParam, {
          app_id: appid
        } );
        if ( typeof after === 'undefined' ) {
          after = before;
          before = undefined;
        }

        if ( $.isFunction( before ) ) {
          before();
        }
        $( '.keywords_rule_list', keywordsReply ).empty();
        $.ajax( {
          url: thisApis.GET_KEYWORDREPLY,
          type: 'post',
          data: fnThis.queryParam,
          success: function( data ) {
            data = $.parseJSON( data );
            console.log( data.data )
            window[ 'autoReplyFlag' + 2 ] = !0;
            if ( $.isFunction( after ) ) {
              after.apply( window, arguments );
            }
            if ( !data.ret ) {
              if ( data.data.data && data.data.data.length ) {
                htmlAndDataset.keywordReply.init( data.data.data );
                if ( !fnThis.resetPage ) {
                  pageChangeRander( data.data.count );
                  fnThis.resetPage = !0;
                }
              } else {
                if ( !fnThis.queryParam.search ) {
                  $( '.nodata_prompt', keywordsReply ).removeClass( 'hide' );
                }
              }
            }
          },
          complete: function() {
            $( '.spinner', keywordsReply ).hide();
            if ( !fnThis.queryParam.search ) {
              ShowTitleMessage.hide();
            }
          }
        } );
      },
      search: function( searchStr ) {
        var fnThis = this;
        $.extend( fnThis.queryParam, {
          search: searchStr
        } );
        fnThis.freshReset().freshRules( function( data ) {
          if ( !data.data || !data.data.data.length ) {
            ShowTitleMessage.showWarning( '没有搜索到相关数据', showTime );
          }
        } );
      },
      kwordCtrlHtml: function( json ) {
        var html = '';

        html += '<li class="keyword_item">';
        html += '<span class="show_text">' + json.keyword + '</span>';
        html += '<span class="glyphicon glyphicon-trash pull-right keyword_edit keyword_delete"></span>';
        html += '<span class="iconfont icon-edit pull-right keyword_edit" data-toggle="modal" data-target="#modify_reply_keyword"></span>';
        html += '<a href="javascript: void(0);" class="pull-right js_match_rule">' + ( parseInt( json.is_full_match ) ? '完全匹配' : '未全匹配' ) + '</a>';
        html += '</li>';

        return $( html ).data( 'kwData', json );
      },
      replyContent: [
        function( json ) {
          var html = '';
          html += '<li class="content_item">';
          html += '<span>' + ( json.text || '' ) + '</span>';
          html += '<span class="glyphicon glyphicon-trash pull-right content_edit js_content_delete"></span>';
          html += '<span class="iconfont icon-edit pull-right content_edit js_text_edit" data-toggle="modal" data-target="#Js_textEditor"></span>';
          html += '</li>';
          return $( html ).data( 'ruleData', json );
        },
        function( json ) {
          var html = '';
          html += '<li class="content_item">';
          html += '<a class="img_type" href="' + json.img_url + '" target="_blank" style="background-image: url(' + json.img_url + ')"></a>';
          html += '<span class="glyphicon glyphicon-trash pull-right content_edit js_content_delete"></span>';
          html += '</li>';
          return $( html ).data( 'ruleData', json );;
        },
        function() {

        },
        function( json ) {
          var html = '';

          html += '<li class="content_item">';
          html += htmlBuild.getVideoHtml( {
            video_title: json.video_title,
            value: json.video_url,
            video_summary: json.video_synopsis,
          } );
          html += '<span class="glyphicon glyphicon-trash pull-right content_edit js_content_delete"></span>';
          html += '</li>';

          return $( html ).data( 'ruleData', json );;
        },
        function( json ) {
          var html = '';
          html += '<li class="content_item">';
          html += htmlBuild.getGraphHtml( json.article );
          html += '<span class="glyphicon glyphicon-trash pull-right content_edit js_content_delete"></span>';
          html += '</li>';

          return $( html ).data( 'ruleData', json );;
        }
      ]

    }
  };
  var deleteHtml = '<a href="javascript: void(0);" class="del_content">删除</a>';

  var htmlContentAppend = [
    function( data ) {
      $( '.tab_text ', this ).trigger( 'click' );
      $( '.js_editorArea', this ).text( data.text ).trigger( 'keyup' );
    },
    function( data ) {
      var imgArea = $( '.js_imgArea', this );
      $( '.tab_img', this ).trigger( 'click' );
      $( '.tab_cont_cover', imgArea ).hide();
      $( '.wait_content', imgArea ).hide().html( htmlBuild.getImgHtml( data.img_url ) ).append( deleteHtml ).show();
    },
    function() {},
    function( data ) {
      var videoArea = $( '.js_videoArea', this );
      $( '.tab_video ', this ).trigger( 'click' );

      $( '.tab_cont_cover', videoArea ).hide();
      $( '.wait_content', videoArea ).hide().html( htmlBuild.getVideoHtml( {
        video_title: data.video_title,
        value: data.video_url,
        video_summary: data.video_summary,
      } ) ).append( deleteHtml ).show();
    }
  ];

  !( function() {
    var rm = $( '.replymsg1', me );

    rm.on( 'click', '.dosave', function() {
      var thisBtn = $( this );
      if ( !beforeSaveCheck( rm ) ) return;
      thisBtn.prop( 'disabled', 'disabled' );
      ShowTitleMessage.show( '正在保存' );
      $.ajax( {
        url: thisApis.SAVE_BEADDEDREPLY,
        type: 'post',
        data: {
          beadded_reply: JSON.stringify( replyData.beadded )
        },
        success: function( data ) {
          data = $.parseJSON( data );
          if ( !data.ret ) {
            ShowTitleMessage.show( '保存成功！', showTime );
            $( '.delete_reply', rm ).removeAttr( 'disabled' );
          } else {
            ShowTitleMessage.showWarning( data.msg, showTime );
          }
        },
        complete: function() {
          thisBtn.removeAttr( 'disabled' );
        }
      } );
    } ).on( 'click', '.delete_reply', function() {

      bc.deleteConfirmShowBottom( {
        obj: this,
        url: thisApis.DEL_BEADDEDREPLY,
        type: 'post',
        param: {
          app_id: appid
        },
        text: '删除后，关注公众号的粉丝将不再接收该回复，确认删除？',
        fun: function( data ) {
          data = $.parseJSON( data );
          if ( !data.ret ) {
            ShowTitleMessage.show( '删除成功！', showTime );
            $( '.wait_content', rm ).empty();
            $( '.js_editorArea', rm ).text( '' );
            $( this ).prop( 'disabled', 'disabled' );
          }
        }
      } );
    } ).on( 'blur', '.js_editorArea', function() {
      var thisText = $( this ).text();
      //if (!/^\s*$/.test(thisText)) {}
      if ( thisText.length > 600 ) return;

      htmlAndDataset.beaddedSetAttrbute( {
        type: 'text',
        text: thisText
      } );
    } );

  }() );

  ( function() {
    var rm = $( '.replymsg2', me );

    rm.on( 'click', '.dosave', function() {

      var thisBtn = $( this );
      if ( !beforeSaveCheck( rm ) ) return;
      thisBtn.prop( 'disabled', 'disabled' );
      ShowTitleMessage.show( '正在保存' );
      $.ajax( {
        url: thisApis.SAVE_AUTOREPLY,
        data: {
          autoreply: JSON.stringify( replyData.autoReply )
        },
        type: 'post',
        success: function( data ) {
          data = $.parseJSON( data );
          if ( !data.ret ) {
            ShowTitleMessage.show( '保存成功！', showTime );
            $( '.delete_reply', rm ).removeAttr( 'disabled' );
          } else {
            ShowTitleMessage.showWarning( data.msg, showTime );
          }
        },
        complete: function() {
          thisBtn.removeAttr( 'disabled' );
        }
      } );
    } ).on( 'click', '.delete_reply', function() {
      bc.deleteConfirmShowBottom( {
        obj: this,
        url: thisApis.DEL_AUTOREPLY,
        type: 'post',
        param: {
          app_id: appid
        },
        text: '删除后，关注公众号的粉丝将不再接收该回复，确认删除？',
        fun: function( data ) {
          data = $.parseJSON( data );
          if ( !data.ret ) {
            ShowTitleMessage.show( '删除成功！', showTime );
            $( '.wait_content', rm ).empty();
            $( '.jsMsgSendTab', rm ).show();
            $( '.js_editorArea', rm ).text( '' );
            $( this ).prop( 'disabled', 'disabled' );
          }
        }
      } );
    } ).on( 'blur', '.js_editorArea', function() {

      var thisText = $( this ).text();
      //if (!/^\s*$/.test(thisText)) {}
      if ( thisText.length > 600 ) return;
      htmlAndDataset.autoReplySetAttrbute( {
        type: 'text',
        text: thisText
      } );
    } );

  }() );
  // 被添加自动回复和消息自动回复
  function beforeSaveCheck( dom ) {
    var msgArray = [
      '',
      '文字必须为1到600个字',
      '请添加素材',
      '请添加素材',
      '请添加素材'
    ];
    var selectedIndex = $( '.js_tab_navs .selected', dom ).index(),
      msg = msgArray[ selectedIndex ] || '',
      text;
    if ( selectedIndex == 1 ) {
      text = $.trim( $( '.tab_panel .tab_content .js_editorArea', dom ).text() );
    } else {
      text = $.trim( $( '.tab_panel .tab_content', dom ).eq( selectedIndex ).find( '.wait_content' ).html() );
    }
    if ( !text ) {
      ShowTitleMessage.showWarning( msg, showTime );
      return 0;
    }

    return !0;
  }

  var rm = $( '.replymsg3', me ),
    currentRuleDom = null,
    currentKeyword = null;

  ( function() {

    ruleHTML = $( $.trim( $( '#keywordsHTML' ).html() ) ),
      ak = $( '#add_reply_keyword', rm ),
      mk = $( '#modify_reply_keyword', rm ),
      te = $( '#Js_textEditor', rm ),
      editTextContent = null;
    ruleHTML.data( 'keywordData', kw.data() ).appendTo( '.create_new_rule_box' ).find( '.reply_type_control .control_item' ).tooltip();

    rm.on( 'click', '.add_rules', function() {

      if ( $( '.create_new_rule_box', rm ).hasClass( 'hide' ) ) {
        $( '.create_new_rule_box', rm ).removeClass( 'hide' );
      } else {
        $( '.create_new_rule_box', rm ).addClass( 'hide' );
        $( '.create_new_rule_box .fm_data', rm )[ 0 ].reset();
      }

    } ).on( 'keydown', '.js_addkeyword', function( e ) {
      e = e || event;
      if ( e.keyCode == 13 ) {
        var thisVal = $.trim( $( this ).val() );
        if ( !thisVal ) return false;
        $( this ).val( '' );
        $( '.keyword_preview', ak ).append( '<span class="kp_item">' + thisVal + '</span>' );
        return false;
      }
    } ).on( 'click', '.keyword_preview .kp_item', function( e ) {
      $( this ).remove();
    } ).on( 'click', '.new_rule .head_tab', function() {
      if ( $( this ).next( '.body_tab' ).css( 'display' ) != 'none' ) {
        $( this ).next( '.body_tab' ).slideUp().next( '.foot_tab' ).slideUp().next( '.simple_info' ).slideDown();
        $( this ).find( '.glyphicon' ).transition( {
          'rotate': '180deg'
        } );
      } else {
        $( this ).next( '.body_tab' ).slideDown().next( '.foot_tab' ).slideDown().next( '.simple_info' ).slideUp();
        $( this ).find( '.glyphicon' ).transition( {
          'rotate': '0deg'
        } );
      }
    } ).on( 'click', '.keywords_rule_list .js_delete_rule,.keywords_rule_list .js_delete_rule_simple', function() {
      var id = $( this ).parents( '.new_rule' ).data( 'keywordData' ).id;
      bc.deleteConfirmShowBottom( {
        obj: this,
        text: '确认要删除规则吗？',
        msg: '正在删除',
        url: thisApis.DEL_KEYWORDREPLY,
        type: 'post',
        param: {
          rule_id: id
        },
        fun: function( data ) {
          data = $.parseJSON( data );
          if ( !data.ret ) {
            ShowTitleMessage.show( '删除成功', showTime );
            $( this ).parents( '.new_rule' ).slideUp( function() {
              $( this ).remove();
            } );
          } else {
            ShowTitleMessage.showWarning( '删除失败！', showTime );
          }
        }
      } );
    } ).on( 'click', '.create_new_rule_box .js_delete_rule,.create_new_rule_box .js_delete_rule_simple', function() {
      bc.deleteConfirmShowBottom( {
        obj: this,
        text: '确认要删除规则吗？',
        fun: function() {
          $( '.create_new_rule_box', rm ).addClass( 'hide' );
          $( '.create_new_rule_box .fm_data', rm )[ 0 ].reset();
        }
      } );
    } ).on( 'click', '.new_rule .dosave', function() {
      var $rule = $( this ),
        $parent = $rule.parents( '.new_rule' ),
        rule = $parent.data( 'keywordData' ),
        kwArray = [],
        cttArray = [];
      $( '.keyword_list .keyword_item', $parent ).each( function( index, item ) {
        kwArray.push( $( item ).data( 'kwData' ) );
      } );
      rule.keywords = kwArray;

      $( '.reply_content_list .content_item', $parent ).each( function() {
        cttArray.push( $( this ).data( 'ruleData' ) );
      } );
      rule.rules = cttArray;
      if ( !saveCheck( rule ) ) return;
      $rule.prop( 'disabled', 'disabled' );
      ShowTitleMessage.show( '正在保存' );
      $.ajax( {
        type: 'post',
        url: thisApis.SAVE_KEYWORDREPLY,
        data: {
          keywordreply: JSON.stringify( rule )
        },
        success: function( data ) {
          data = $.parseJSON( data );
          if ( !data.ret ) {
            ShowTitleMessage.show( '保存成功', showTime );
            if ( !rule.id ) {
              htmlAndDataset.keywordReply.freshReset().freshRules();
              $( '.create_new_rule_box', rm ).addClass( 'hide' ).find( '.fm_data' )[ 0 ].reset();
            } else {

            }
          } else if ( data.ret * 1 === 20110 ) {
            ShowTitleMessage.showWarning( data.msg, showTime );
          } else {
            ShowTitleMessage.showWarning( '保存失败', showTime );
          }
        },
        complete: function() {
          $rule.removeAttr( 'disabled' );
        }
      } );
    } ).on( 'click', '.js_addkword', function() {
      currentRuleDom = $( this ).parents( '.new_rule' );
      if ( $( this ).parent().next().find( '.keyword_item' ).length >= 10 ) {
        ShowTitleMessage.showWarning( '最多10个关键词', showTime );
        return false;
      }
    } ).on( 'change', '.new_rule .ipt_rule_name', function() {
      var $rule = $( this ),
        thisText = $rule.val(),
        $dataContainer = $rule.parents( '.new_rule' ),
        ruleJson = $dataContainer.data( 'keywordData' );
      $rule.val( $.trim( thisText ) );
      $rule.parents( '.new_rule' ).find( '.rule_name_text .name' ).text( $rule.val() );
      $dataContainer.data( 'keywordData', $.extend( ruleJson, {
        rule_name: $rule.val()
      } ) );
    } ).on( 'click', '.keyword_edit', function() {

      currentKeyword = $( this ).parent();
      $( '.js_addkeyword', mk ).val( $( this ).parent().data( 'kwData' ).keyword ).focus();

    } ).on( 'click', '.keyword_delete', function() {
      var $newRule = $( this ).parents( '.new_rule' );
      $( this ).parent().remove();
      $newRule.find( '.simp_kw_list' ).empty();
      $( this ).parent().parent().find( '.keyword_item' ).each( function() {
        $newRule.find( '.simp_kw_list' ).append( '<span class="keyword_item">' + $( '.show_text', this ).text() + '</span>' );
      } );

    } ).on( 'click', '.js_match_rule', function() {

      var fullMatch = $( this ).parent().data( 'kwData' );
      if ( fullMatch.is_full_match * 1 ) {
        $.extend( fullMatch, {
          is_full_match: 0
        } );
        $( this ).text( '未全匹配' );
      } else {
        $.extend( fullMatch, {
          is_full_match: 1
        } );
        $( this ).text( '完全匹配' );
      }
      $( this ).parent().data( 'kwData', fullMatch );

    } ).on( 'click', '.reply_type_control .control_item', function( e ) {

      currentRuleDom = $( this ).parents( '.new_rule' );
      if ( $( this ).hasClass( 'text_control' ) ) {
        $( '.modal-title', te ).text( '添加回复文字' );
      }
      if ( $( this ).parent().next().find( '.content_item' ).length >= 5 ) {
        e.preventDefault();
        ShowTitleMessage.showWarning( '最多5个回复', showTime );
        return false;
      }

    } ).on( 'click', '.reply_content_list .js_content_delete', function() {
      var $newRule = $( this ).parents( '.new_rule' );
      $( this ).parent().remove();
      htmlAndDataset.keywordReply.countCacul.call( $newRule );


    } ).on( 'reset', '.fm_data', function() {
      $( '.keyword_list', this ).empty();
      $( '.reply_content_list', this ).empty();
      $( '.simp_data>span', this ).text( 0 );
      $( this ).parent().data( 'keywordData', kw.data() );
    } ).on( 'click', '.search_btn', function() {
      ShowTitleMessage.show( '正在搜索' );
      htmlAndDataset.keywordReply.search( $.trim( $( this ).prev().val() ) );
    } ).on( 'click', '.js_text_edit', function() {
      var ruleData = $( this ).parent().data( 'ruleData' );
      editTextContent = $( this ).parent();
      $( '.modal-title', te ).text( '修改回复文字' );
      $( '.js_editorArea', te ).val( ruleData.text || '' ).trigger( 'keyup' );
    } );

    ak.on( 'hidden.bs.modal', function() {

      $( '.js_addkeyword', this ).val( '' );
      $( '.keyword_preview', this ).empty();

    } ).on( 'click', '.btn-success', function() {

      var text = $( '.js_addkeyword', ak );
      var thisText = $.trim( text.val() );

      if ( thisText ) {
        $( '.keyword_preview', ak ).append( '<span class="kp_item">' + text.val() + '</span>' );
      }

      $( '.keyword_preview .kp_item', ak ).each( function( index, item ) {
        var param = {
          keyword: $( item ).text(),
          is_full_match: '1'
        };
        $( '.keyword_list', currentRuleDom ).append( htmlAndDataset.keywordReply.kwordCtrlHtml( param ) );
        $( '.simp_kw_list', currentRuleDom ).append( '<span class="keyword_item">' + $( item ).text() + '</span>' );
      } );

      text.val( '' );
      $( '.keyword_preview', ak ).empty();
      ak.modal( 'hide' );

    } );

    mk.on( 'hidden.bs.modal', function() {
      $( '.js_addkeyword', mk ).val( '' );
    } ).on( 'click', '.btn-success', function() {
      var text = $( '.js_addkeyword', mk )
      if ( $.trim( text.val() ).length == 0 ) {
        ShowTitleMessage.showWarning( '关键词不能为空', showTime );
        return;
      }
      var currentData = currentKeyword.data( 'kwData' );
      var $html = htmlAndDataset.keywordReply.kwordCtrlHtml( {
        keyword: $.trim( text.val() ),
        is_full_match: currentData.is_full_match
      } );
      currentKeyword.before( $html ).remove();

      mk.modal( 'hide' );

    } );

    te.on( 'hidden.bs.modal', function() {
      $( '.js_editorArea', this ).val( '' );
      $( '.editor_tip', this ).text( '还可以输入' + $( '.js_editorArea', this ).prop( 'maxlength' ) + '字' );
      editTextContent = null;
    } ).on( 'click', '.btn-success', function() {
      var textCon = $.trim( $( '.js_editorArea', te ).val() );
      if ( !textCon ) {
        ShowTitleMessage.showWarning( '文字不能为空', showTime );
        return;
      }
      var $htmlObj = htmlAndDataset.keywordReply.replyContent[ 0 ]( {
        type: 'text',
        text: textCon
      } );
      if ( editTextContent ) {
        editTextContent.before( $htmlObj );
        editTextContent.remove();
      } else {
        $htmlObj.appendTo( $( '.reply_content_list', currentRuleDom ) );
        htmlAndDataset.keywordReply.countCacul.call( currentRuleDom );
      }

      te.modal( 'hide' );
    } );

    // 保存前验证
    function saveCheck( ruleJson ) {
      if ( !ruleJson.rule_name ) {
        ShowTitleMessage.showWarning( '规则名不能为空', showTime );
        return 0;
      } else if ( ruleJson.rule_name.length > 60 ) {
        ShowTitleMessage.showWarning( '规则名最多60个字', showTime );
        return 0;
      }

      if ( !ruleJson.keywords.length ) {
        ShowTitleMessage.showWarning( '请至少输入1个关键词', showTime );
        return 0;
      } else if ( ruleJson.keywords.length > 10 ) {
        ShowTitleMessage.showWarning( '最多只能输入10个关键词', showTime );
        return 0;
      }

      if ( !ruleJson.rules.length ) {
        ShowTitleMessage.showWarning( '请至少输入1个回复', showTime );
        return 0;
      }

      return !0;
    }
  }() );

  return returnParam;

} );
